# coding: utf8

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################  

import urllib2

from xml.sax import parseString, make_parser
from xml.sax.handler import ContentHandler

genres_dict=[]
artists_dict=[]

class ListHandler(ContentHandler):
    def startElement(self,name,attrs):
 
        # print 'start element', name
        # for x in name:
        genres_dict.append(name)
        return genres_dict

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html
    """
    # response.flash = T('Welcome to web2py')

    # response = urllib2.urlopen('http://api.npr.org/query?id=14996733&output=ATOM&numResults=100&apiKey=MDAxNzgwMDQ5MDEyMTQ4NzYyMjU4YmY1Yw004')
    
    genres_url = urllib2.urlopen('http://api.npr.org/list?id=3018')
    genres_xml = genres_url.read()

    artists_url = urllib2.urlopen('http://api.npr.org/list?id=3009')
    artists_xml = artists_url.read()

    # return dict(message = T(genres_xml))
    # return dict(message = T(artists_xml))

    list_handler = ListHandler()

    sax_parser = make_parser()
    sax_parser.setContentHandler(list_handler)
    
    # this might work if we were working with a file    
    # sax_parser.setContentHandler(list_handler)
    # sax_parser.parse(artists_xml, list_handler)

    # however, we're working with a string
    sax_parser = parseString(artists_xml, list_handler)

    # info = type(artists_xml)

    # return dict(message=T(info))
    
    info = genres_dict 

    # info = 'Hello World'
    # return dict(message=T(info))
    return info

def user():
    """
    exposes:
    http://..../[app]/default/user/login 
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())

def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    session.forget()
    return service()
